package com.ldgk.pim.client.presenter;

import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.search.client.AddressLookupMode;
import com.google.gwt.search.client.LocalResult;
import com.google.gwt.search.client.LocalSearch;
import com.google.gwt.search.client.ResultSetSize;
import com.google.gwt.search.client.SearchCompleteHandler;
import com.ldgk.pim.client.event.GLocalSearchEvent;
import com.ldgk.pim.client.util.Util;
import com.ldgk.pim.client.view.MainView;

/**
 * Main presenter, handles toolbars and external buttons events
 * @version 1.0
 *
 */
public class MainPresenter implements Presenter, SearchCompleteHandler{
	private MainView mainView;
	
	private static boolean firstResultArrived=false;
	
	/** Google local search component */
	private final LocalSearch googleSearch = new LocalSearch();
	
	public MainPresenter(MainView mainView){
		this.mainView = mainView;
		this.mainView.setPresenter(this);
		
		this.googleSearch.setAddressLookupMode(AddressLookupMode.ENABLED);
		this.googleSearch.setResultSetSize(ResultSetSize.LARGE);
		this.googleSearch.addSearchCompleteHandler(this);
	}
	
	/**
	 * Start a google local search
	 * @param centerPoint - map center point (contextual search)
	 * @param query - string to be queried
	 */
	public void performLocalSearch(LatLng centerPoint, String query){
		firstResultArrived=false;
		this.googleSearch.setCenterPoint(centerPoint);
  		this.googleSearch.execute(query);
	}

	/**
	 * On google local search complete (new result arrived)
	 */
	public void onSearchComplete(SearchCompleteEvent event) {
		LocalResult lres = (LocalResult) event.getResult();
		if(!firstResultArrived){
			firstResultArrived=false;
			Util.mapView.setMapCenter(LatLng.newInstance(lres.getLat(), lres.getLng()));
		}
		GLocalSearchEvent newResult = new GLocalSearchEvent(lres);
		Util.eventbus.fireEvent(newResult);
	}
}
